/**
 * 设备表格
 */
import React, {Component} from 'react';
import {Table, Modal, message} from 'antd';
import {connect} from 'dva';
import {Link} from 'dva/router';
import moment from 'moment';
import _ from 'lodash';
import {defaultData, unLockDevice, api} from '../../services/device';
import getPagination from '../../components/pagination';
import {onSetItemDecorator} from '../../components/export';
import {isSuccess} from '../../configs/error';
import {isReleaseVersion, getPermission} from '../../components/permissionControl';

export const columns = [
  {
    title: '设备MAC',
    dataIndex: 'mac',
    key: 'mac',
  },
  {
    title: '序列号',
    dataIndex: 'sno',
    key: 'sno'
  },
  {
    title: '设备名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '所属产品',
    dataIndex: 'product',
    key: 'product'
  },
  {
    title: '场地名称',
    dataIndex: 'deviceLocation',
    key: 'deviceLocation'
  },
  {
    title: '当前归属',
    dataIndex: 'belongOperatorName',
    key: 'belongOperatorName'
  },
  // {
  // 	title: '收费名称',
  // 	dataIndex: 'serviceMode',
  // 	key: 'serviceMode'
  // },
  // {
  //   title: '最后上线时间',
  //   dataIndex: 'lastOnLineTime',
  //   render: (text, record) => record.lastOnLineTime ? moment(record.lastOnLineTime).format('YYYY-MM-DD HH:mm:ss') : '',
  //   key: 'lastOnLineTime'
  // },
  // {
  // 	title: '设备状态',
  // 	dataIndex: 'workStatusDesc',
  // 	key: 'workStatusDesc'
  // },
  {
    title: '在线状态',
    dataIndex: 'onlineStatus',
    key: 'onlineStatus'
  },
  // {
  // 	title: '激活状态',
  // 	dataIndex: 'activateStatusDesc',
  // 	key: 'activateStatusDesc'
  // },
  {
    title: '操作',
    key: 'opt',
    // 运营商和代理设备列表操作详情
    render: (text, record) => {
      return <Link to={`/deviceList/${record.sno}`}>详情</Link>
    }
  }
];

const {confirm} = Modal;

@onSetItemDecorator
class DeviceTable extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      queryData: {...defaultData.query},
      page: 1,
      size: 10
    };
  }

  componentWillMount() {
    this.query();
  }

  componentWillReceiveProps(nextProps) {
    if (!_.isEqual(nextProps.query, this.props.query)) {
      this.setState({page: 1});
    }
  }

  componentDidUpdate(prevProps, prevState) {
    const {page, size} = this.state;
    if (!_.isEqual(prevProps.query, this.props.query) || page !== prevState.page || size !== prevState.size) {
      this.query();
      // this.props.query({ ...queryData });
    }
  }

  onChange = selectedRowKeys => {
    this.props.select(selectedRowKeys);
  };

  unLock = (record) => {
    confirm({
      title: '解除锁定',
      content: '确定要解除锁定吗?',
      onOk: () => this.confirmUnlock(record),
    });
  }

  confirmUnlock = async (record) => {
    const {dispatch} = this.props;
    const res = await unLockDevice(record.sno);
    if (isSuccess(res)) {
      message.success('解除锁定成功');
      dispatch({
        type: 'device/query',
        payload: {},
      });
    }
  }

  renderOpt = (text, record, isRelease) => (
    <div>
      {(isRelease && record.lock) && <a style={{marginRight: 15}} onClick={() => this.unLock(record)}>解除锁定</a>}
      <Link to={`/deviceList/${record.sno}`}>详情</Link>
    </div>
  )

  columns = columns.map(c => c.key === 'opt' ? {...c, render: this.renderOpt} : c)

  query() {
    // 请求数据
    const {dispatch, query} = this.props;
    const {page, size} = this.state;
    const queryData = {...this.state.queryData};
    if (query) {
      queryData.query ? queryData.query = {...queryData.query, ...query} : queryData.query = query;
    }
    dispatch({
      type: 'device/query',
      payload: {
        ...queryData,
        current: page,
        size
      }
    });
  }

  pageChange = page => {
    this.setState({page});
  }

  pagesizgeChange = (current, size) => {
    this.setState({page: 1, size});
  }

  render() {
    const {select, selectedRowKeys, user: {permissions = []}, list, pagination, notShow = [], loading, ...props} = this.props;
    const {page} = this.state;
    const rowSelection = select ? {
      onChange: this.onChange,
      selectedRowKeys
    } : null;
    const isRelease = isReleaseVersion(permissions, api.unLockDevice);
    let showColumns = columns.map(c => c.key === 'opt' ? {
      ...c,
      render: (text, record) => this.renderOpt(text, record, isRelease)
    } : c);
    if (!getPermission(permissions, api.detail)) showColumns = columns.filter(c => c.key !== 'opt');
    console.log(showColumns.filter(c => !notShow.includes(c.key)));
    console.log(list);
    return (
      <div>
        <Table
          dataSource={list}
          columns={showColumns.filter(c => !notShow.includes(c.key))}
          pagination={getPagination({
            current: page,
            onChange: this.pageChange,
            total: pagination.total,
            onShowSizeChange: this.pagesizgeChange
          })}
          loading={loading.effects['device/query']}
          rowSelection={rowSelection}
          {...props}
          rowKey="sno"
        />
      </div>
    );
  }
}

DeviceTable.propTypes = {};

export default connect(
  ({device, app, loading}) => ({
    loading,
    pagination: device.pagination,
    list: device.list,
    tableDisplay: device.tableDisplay,
    user: app.user
  })
)(DeviceTable);

